<?php

class AdminPostController extends MController {

    public function indexAction() {
        $posts = Post::all(array('order' => 'id DESC'));
        $postsTable = new MHtmlTable($posts, array('created_at', 'updated_at'));
        $buttons = array(
            'update' => array('title' => 'Mise à jour', 'href' => __route('ml-admin', array('module' => 'ml-blog/post/update', 'id' => '{id}')), 'content' => 'Update'),
            'delete' => array('title' => 'Supprimer', 'href' => __route('ml-admin', array('module' => 'ml-blog/post/delete', 'id' => '{id}')), 'content' => 'Supprimer')
        );
        $postsTable->addColumn(new MHtmlButtonColumn($postsTable, $buttons));

        if ($this->getRequest()->isAjax()) {
            $this->renderPartial('index', array(
                'postsTable' => $postsTable
                    )
            );
        } else {
            $this->render('index', array(
                'postsTable' => $postsTable
                    )
            );
        }
    }

    public function quickPublishAction() {
        $form = new QuickPublishForm();
        $errorMessages = array();
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();
            $form->bindData($post);
            if ($form->isValid($post)) {
                try {
                    Post::create(array('title' => $post['postTitle'], 'html_content' => $post['postContent']));
                } catch (Exception $exc) {
                    array_push($errorMessages, $exc->getMessage());
                }
            } else {
                $errorMessages = $form->getErrors();
            }
        }
        $this->renderPartial('quickPublish', array('form' => $form, 'errorMessages' => $errorMessages));
    }

    public function createAction() {
        $form = new PostCreateForm();
        $errorMessages = array();
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();
            $form->bindData($post);
            if ($form->isValid($post)) {
                try {
                    $userId = MSession::getInstance()->getUserID();
                    $profile = Profile::find(array('user_id' => $userId));
                    Post::create(
                                    array(
                                        'title' => $post['postTitle'],
                                        'html_content' => $post['postContent'],
                                        'profile_id' => $profile->id,
                                        'status_id' => $post['postStatus']
                                    )
                    );
                } catch (Exception $exc) {
                    array_push($errorMessages, $exc->getMessage());
                }
            } else {
                $errorMessages = $form->getErrors();
            }
        }
        $this->render('create', array('form' => $form, 'errorMessages' => $errorMessages));
    }

}

?>
